Type casting, also known as type conversion, is a way to convert a variable from one data type to another. In C, type casting is used to ensure compatibility between different data types during expressions or assignments. Sometimes, the data type of an expression needs to be explicitly converted to the desired type to avoid data loss or perform specific operations.
To perform type casting in C, use the desired data type enclosed in parentheses before the expression or variable that want to convert.
data_type new_variable = (data_type) old_variable;
#include <stdio.h>
int main() {
int num1 = 10;
int num2 = 3;
float result;
// Performing type casting to get the floating-point division result
result = (float)num1 / num2;
printf("Floating-point division result: %f\n", result);
// Type casting to get the integer division result (truncates decimal part)
int integerResult = (int)(num1 / num2);
printf("Integer division result: %d\n", integerResult);
return 0;
}
Floating-point division result: 3.333333
Integer division result: 3
Note: Type casting is important when dealing with expressions involving mixed data types. It helps to avoid unexpected behaviour and ensure correct results. However, be cautious while performing type casting, as it may lead to data loss if the converted value is outside the range of the target data type.
What is type casting in C?
What is an implicit type cast in C?
What is an explicit type cast in C?